// pages/add-new-addr/index.js
var url = getApp().globalData.ApiUrl;
var addressDataKey = 'addressDataKey';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 地址数据库
    addressData: [],
    provinceArray: [],
    cityArray: [],
    districtArray: [],
    provinceIndex: 0,
    cityIndex: 0,
    districtIndex: 0,
    showArea: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    
    that.loadAddressData();
    
  },
  loadAddressData: function () {
    wx.showLoading({
      title: '加载中，请稍后...',
    });
    var that = this;
    // 拉取地址数据库保存到本地
    // TODO 网络异常处理
    wx.request({
      url: 'https://api.zhuisushangcheng.com/mobile/index.php?act=area&op=getAreaListAll',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      success: function (res) {
        if (res.data.code == 200) {
          wx.hideLoading();
          wx.setStorageSync(addressDataKey, res.data.datas.area_list);
          that.setData({
            addressData: res.data.datas.area_list
          })
          if (!res.data.datas.area_list) {
            that.loadAddressData()
          }
          // 初始化地址选择
          that.initAddressPicker();
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            }) 
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 初始化地址选择
  initAddressPicker: function () {
    // 初始化地址选择器数据  
    this.setData({
      provinceIndex: 0,
      cityIndex: 0,
      districtIndex: 0,
    })
    this.refreshPicker();
  },
  // 获取省数据数组
  getProvinceArray: function () {
    var provinceArray = [];
    this.data.addressData.forEach(function (i) {
      provinceArray.push(i.area_name);
    })
    return provinceArray
  },
  // 获取市数据数组
  getCityArray: function (provinceIndex) {
    var cityArray = []
    this.data.addressData[provinceIndex].list.forEach(function (i) {
      cityArray.push(i.area_name);
    })
    return cityArray
  },
  // 获取区数据数组
  getDistrictArray: function (provinceIndex, cityIndex) {
    var districtArray = []
    this.data.addressData[provinceIndex].list[cityIndex].list.forEach(function (i) {
      districtArray.push(i.area_name);
    })
    return districtArray
  }, 

  refreshPicker: function () {
    // 根据index的变动，刷新选择器以及下一级array的数据

    var provinceIndex = this.data.provinceIndex
    var cityIndex = this.data.cityIndex
    var districtIndex = this.data.districtIndex

    var provinceArray = this.getProvinceArray()
    var cityArray = this.getCityArray(provinceIndex)
    var districtArray = this.getDistrictArray(provinceIndex, cityIndex)

    this.setData({
      provinceArray: provinceArray,
      cityArray: cityArray,
      districtArray: districtArray,

      provinceIndex: provinceIndex,
      cityIndex: cityIndex,
      districtIndex: districtIndex,
    })
  },

  provinceChange: function (e) {
    var provinceIndex = parseInt(e.detail.value)
    if (provinceIndex < 0) {
      this.setData({
        showArea: false
      })
    } else {
      this.setData({
        showArea: true
      })
    };
    this.setData({
      provinceIndex: provinceIndex,
      cityIndex: 0,
      districtIndex: 0,
    })
    this.refreshPicker()

  },

  cityChange: function (e) {
    var cityIndex = e.detail.value
    this.setData({
      cityIndex: cityIndex,
      districtIndex: 0,
    })
    this.refreshPicker()
  },

  districtChange: function (e) {
    var districtIndex = e.detail.value
    this.setData({
      districtIndex: districtIndex,
    })
    this.refreshPicker()

  },
  formSubmit: function (e) {
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
    var addressData = wx.getStorageSync(addressDataKey);
    // var city_id = addressData[this.data.provinceIndex].area_id;
    var city_id = addressData[this.data.provinceIndex].list[this.data.cityIndex].area_id;
    var area_id = addressData[this.data.provinceIndex].list[this.data.cityIndex].list[this.data.districtIndex].area_id;
    var area_info = addressData[this.data.provinceIndex].area_name + ' ' + addressData[this.data.provinceIndex].list[this.data.cityIndex].area_name + ' ' + addressData[this.data.provinceIndex].list[this.data.cityIndex].list[this.data.districtIndex].area_name;
    var true_name = e.detail.value.true_name;
    var mob_phone = e.detail.value.mob_phone;
    var address = e.detail.value.address;
    var key = wx.getStorageSync('key');
    //判断收货人
    if (true_name == "") {
      wx.showModal({
        title: '提示',
        content: '请填写联系人姓名',
        showCancel: false
      })
      return
    }
    //验证手机号码
    if (mob_phone.length == 0) {
      wx.showModal({
        title: '提示',
        content: '请填写手机号码',
        showCancel: false
      })
      return
    } else if (mob_phone.length <11){
      wx.showToast({
        title: '手机号长度有误！',
        icon: 'none',
        duration: 2000
      });
      return false;
    } else if (!myreg.test(mob_phone)){
      wx.showToast({
        title: '手机号有误！',
        icon: 'none',
        duration: 1500
      });
      return false;
    }
    //判断地址是否为空
    if (address == "") {
      wx.showModal({
        title: '提示',
        content: '请填写详细地址',
        showCancel: false
      })
      return
    }
    wx.showLoading({
      title: '加载中，请稍后...',
    });
    wx.request({
      url: url + '/mobile/index.php?act=member_address&op=address_add',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'POST',
      data: {
        key: key,
        true_name: true_name,
        mob_phone: mob_phone,
        city_id: city_id,
        area_id: area_id,
        area_info: area_info,
        address: address,
        is_default: true
      },
      success: (res)=>{
        if(res.data.code ==200){
          wx.hideLoading();
          wx.showToast({
            title: '新增地址成功',
            icon: 'none',
            duration: 2000
          })
          wx.navigateBack({
            delta: 1
          })
        }else{
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    })
  }
  
})